<!-- 审计日志 -->
<template>
  <div class="dashboard-editor-container">
    <div>
      <div style="display:flex;justify-content:space-between;">
        <partitionTree :nodeData="nodeData" :expandArray="expandArray" :addTemplate="false" :defaultExpandAll="false" dialogName="WindowsSystemLog"
          @handleNodeClick="handleNodeClick" ref="partitionTree" @toggleVisibility="toggleVisibility">
        </partitionTree>
        <div :style="{ width: containerWidth }" class="box"
          style="background:#fff;border: 1px solid #ddd;border-radius: 4px;box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.1);">
          <el-row style="background: #fff; padding: 16px 16px 0;">
            <connsearch ref="connsearch" :formOptions="formOptions" @search="search" @reset="reset" />
            <div class="tabclick">
              <div class="tabitem" @click="handleClick()">
                <span><i :class="tab ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i></span>
              </div>
            </div>
            <el-row>
              <el-tabs type="border-card" v-if="tab" style="margin-top:16px;" @tab-click="tabClick">
                <el-tab-pane label="按日统计分析" lazy>
                  <el-col :xs="24" :sm="24" :lg="24">
                    <barchart :chartData="barchartData" @barclick="echartsClick" title="按日统计分析"/>
                  </el-col>
                </el-tab-pane>
                <el-tab-pane label="按资产名称统计分析" lazy>
                  <el-col :xs="24" :sm="24" :lg="24">
                    <piechart :chartData="pie1Data" @pieclick="echartsClick" title="按资产名称统计分析" />
                  </el-col>
                </el-tab-pane>
                <el-tab-pane label="按来源统计分析" lazy>
                  <el-col :xs="24" :sm="24" :lg="24">
                    <piechart :chartData="pie2Data" @pieclick="echartsClick" title="按来源统计分析" />
                  </el-col>
                </el-tab-pane>
                <el-tab-pane label="按事件类型统计分析" lazy>
                  <el-col :xs="24" :sm="24" :lg="24">
                    <piechart :chartData="pie3Data" @pieclick="echartsClick" title="按事件类型统计分析" />
                  </el-col>
                </el-tab-pane>
                <el-tab-pane label="按事件等级统计分析" lazy>
                  <el-col :xs="24" :sm="24" :lg="24">
                    <piechart :chartData="pie4Data" @pieclick="echartsClick" title="按事件等级统计分析" />
                  </el-col>
                </el-tab-pane>
              </el-tabs>
            </el-row>
            <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" style="padding-right: 8px;">
              <!-- <span class="title">事件日志列表</span> -->
              <el-table stripe border :data="tableData" style="width: 100%; margin-top: 32px">
                <el-table-column label="序号" width="60" type="index"
                  :index='(index) => { return (index + 1) + (this.pageNum - 1) * this.pageSize }'> </el-table-column>
                <el-table-column label="部门" show-overflow-tooltip prop="Department" width="120px"></el-table-column>
                <el-table-column label="资产名称" show-overflow-tooltip prop="DeviceName" width="160px"></el-table-column>
                <el-table-column label="使用者" show-overflow-tooltip prop="UserName" width="120px"></el-table-column>
                <el-table-column label="采集时间" prop="TransTime" show-overflow-tooltip width="160px">
                  <template slot-scope="{row}">
                    <span>{{ parseTime(row.TransTime) }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="事件级别" prop="Level" show-overflow-tooltip width="160px"
                  :formatter="LevelFormatter"></el-table-column>
                <el-table-column label="事件类型" prop="EventType" show-overflow-tooltip width="160px"
                  :formatter="EventTypeFormatter"></el-table-column>
                <el-table-column label="事件ID" prop="EventID" show-overflow-tooltip width="160px"></el-table-column>
                <el-table-column label="用户名" prop="LogUser" show-overflow-tooltip width="160px"></el-table-column>
                <el-table-column label="来源" prop="Source" show-overflow-tooltip width="160px"></el-table-column>
                <el-table-column label="摘要" prop="Descp" show-overflow-tooltip></el-table-column>
              </el-table>
              <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page=pageNum
                :page-size=pageSize background layout="total, prev, pager, sizes, next, jumper" :total="total">
              </el-pagination>
            </el-col>
          </el-row>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
import { connrequest } from "@/api/firstPage.js"
import { parseTime, GetDeviceTree2 } from "@/utils/index.js";
import connsearch from "@/components/connSearch";
import barchart from "./components/barchart2.vue";
import piechart from "./components/piechart.vue";
import partitionTree from "@/components/partitionTree";
export default {
  components: { connsearch, barchart, piechart, partitionTree },
  data() {
    let that = this
    return {
      total: 0,
      pageNum: 1,
      pageSize: 10,
      containerWidth: 'calc(100% - 275px)',
      tab: false,
      tableData: [],
      DepartmentList: [],
      pie1Data: [],
      pie2Data: [],
      pie3Data: [],
      pie4Data: [],
      nodeData: [],
      expandArray: [],
      devices: [],
      barchartData: { xAxis: [], series: [] },
      searchform: {},
      nodeobj: {},
      searchobj: {},
      echartsobj: {},
      tabTitle: '按日统计分析',
      formOptions: [
        {
          col: 12,
          label: "日期",
          prop: "timeRange",
          element: "el-date-picker",
          type: "",
          events: {
            input(val) {
              that.searchform.timeRange = val
            }
          }
        },
        {
          col: 6,
          label: "摘要",
          prop: "Descp",
          element: "el-input",
          placeholder: "请输入摘要,支持模糊查询。",
          maxlength: 50,
          events: {
            input(val) {
              that.searchform.Descp = val
            }
          }
        },
        {
          col: 6,
          label: "用户名",
          prop: "UserName",
          element: "el-input",
          placeholder: "请输入用户名",
          maxlength: 50,
          events: {
            input(val) {
              that.searchform.UserName = val
            }
          }
        },
        {
          col: 6,
          label: "事件级别",
          prop: "Level",
          element: "el-select",
          initValue: '',
          placeholder: "请选择事件级别",
          options: [
            { label: "全部", value: '' },
            { label: "关键", value: 1 },
            { label: "错误", value: 2 },
            { label: "警告", value: 3 },
            { label: "信息", value: 4 },
            { label: "详细", value: 5 },
            { label: "审核成功", value: 6 },
            { label: "审核失败", value: 7 },
          ],
          events: {
            input(val) {
              that.searchform.Level = val
            }
          }
        },
        {
          col: 6,
          label: "事件类型",
          prop: "EventType",
          element: "el-select",
          initValue: '',
          placeholder: "请选择事件类型",
          options: [
            { label: "全部", value: '' },
            { label: "应用程序", value: 1 },
            { label: "安全", value: 2 },
            { label: "Setup", value: 3 },
            { label: "系统", value: 4 },
            { label: "转发事件", value: 5 },
            { label: "应用程序和服务日志", value: 6 }
          ],
          events: {
            input(val) {
              that.searchform.EventType = val
            }
          }
        },

        {
          col: 6,
          label: "事件ID",
          prop: "EventID",
          element: "el-input",
          placeholder: "请输入事件ID",
          maxlength: 50,
          events: {
            input(val) {
              that.searchform.EventID = val
            }
          }
        }
      ]
    }
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.pageSize = (Cookies.get('Zhuoguan_DefaultPageLength') || 10) * 1;

    let endTime = new Date(new Date().setHours(0, 0, 0, 0)).getTime()
    let startTime = endTime - ((Cookies.get('Zhuoguan_DefaultLogDays') || 7) * 24 * 3600 * 1000);
    let arr = [parseTime(startTime), '']
    this.formOptions.map(item => {
      if (item.label === '日期') {
        item.initValue = arr
      }
    })
    this.$set(this.searchform, 'timeRange', arr)
    this.getData()
    this.GetWindowsLogSumGroupByDate()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    this.initData()
  },
  methods: {
    parseTime,
    async initData(searchobj = {}) {
      try {
        const { DeviceTree, devices } = await GetDeviceTree2('WindowsSystemLog', {
          StartTime: this.searchform.timeRange?.[0] || '',
          EndTime: this.searchform.timeRange?.[1] || '',
          DeviceUUID: this.searchform.DeviceUUID,
          EventID: (this.searchform.EventID == null || this.searchform.EventID === '') ? '' : this.searchform.EventID == 0 ? 0xFFFFFFFF : this.searchform.EventID * 1,
          EventType: this.searchform.EventType,
          Level: this.searchform.Level,
          UserName: this.searchform.UserName,
          Descp: this.searchform.Descp,
          ...searchobj
        })
        this.devices = devices
        this.nodeData = DeviceTree
        this.expandArray = [DeviceTree?.[0]?.Name]
      } catch (error) {
        this.$message.error('加载设备树数据失败');
      }
    },
    LevelFormatter(val) {
      const levelMap = {
        1: '关键',
        2: '错误',
        3: '警告',
        4: '信息',
        5: '详细',
        6: '审核成功',
        7: '审核失败',
      };
      return levelMap[val.Level] || '未知事件级别';
    },
    EventTypeFormatter(val) {
      const EventTypeMap = {
        1: '应用程序',
        2: '安全',
        3: 'Setup',
        4: '系统',
        5: '转发事件',
        6: '应用程序和服务日志'
      };
      return EventTypeMap[val.EventType] || '未知事件类型';
    },
    handleNodeClick(nodeData) {
      this.pageNum = 1
      this.nodeobj = { DepartmentID: nodeData.data.isDevice ? nodeData.data.DepartmentID : nodeData.data.ID, DeviceUUID: nodeData.data.isDevice ? nodeData.data.DeviceUUID : '' }
      this.echartsobj = {}
      this.getData({ ...this.searchobj, ...this.nodeobj })
    },
    toggleVisibility(isHidden) {
      if (isHidden)
        this.containerWidth = '100%';
      else
        this.containerWidth = 'calc(100% - 275px)';
    },
    async getData(searchobj = {}) {
      this.GetEventLog(searchobj)
      switch (this.tabTitle) {
        case '按日统计分析':
          this.GetWindowsLogSumGroupByDate(searchobj)
          break;
        case '按资产名称统计分析':
          this.GetWindowsLogSumGroupByDevName(searchobj)
          break;
        case '按来源统计分析':
          this.GetWindowsLogSumGroupBySource(searchobj)
          break;
        case '按事件类型统计分析':
          this.GetWindowsLogSumGroupByEventType(searchobj)
          break;
        case '按事件等级统计分析':
          this.GetWindowsLogSumGroupByEventLevel(searchobj)
          break;
      }
    },
    handleClick() {
      this.tab = !this.tab
    },
    async GetEventLog(searchobj = {}) {
      const data = {
        Paging: {
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        },
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || '',
          EndTime: this.searchform.timeRange?.[1] || '',
          DeviceUUID: this.searchform.DeviceUUID,
          EventID: (this.searchform.EventID == null || this.searchform.EventID === '') ? '' : this.searchform.EventID == 0 ? 0xFFFFFFFF : this.searchform.EventID * 1,
          EventType: this.searchform.EventType,
          Level: this.searchform.Level,
          UserName: this.searchform.UserName,
          Descp: this.searchform.Descp,
          ...searchobj
        }
      }
      const res = await connrequest('GetWindowsLogInfo', data)
      res.Data = res.Data || []
      this.tableData = res.Data
      this.total = res.Paging.TotalCount
    },
    // 获取事件日期统计
    async GetWindowsLogSumGroupByDate(searchobj = {}) {
      let xAxis = []
      let series = []
      const data = {
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || '',
          EndTime: this.searchform.timeRange?.[1] || '',
          DeviceUUID: this.searchform.DeviceUUID,
          EventID: (this.searchform.EventID == null || this.searchform.EventID === '') ? '' : this.searchform.EventID == 0 ? 0xFFFFFFFF : this.searchform.EventID * 1,
          EventType: this.searchform.EventType,
          Level: this.searchform.Level,
          UserName: this.searchform.UserName,
          Descp: this.searchform.Descp,
          ...searchobj
        }
      }
      const res = await connrequest('GetWindowsLogSumGroupByDate', data)
      res.Data = res.Data || []
      res.Data.map(item => {
        xAxis.push(item.TransDate)
        series.push(item.Count)
      })
      this.barchartData = { xAxis, series }
    },
    async GetWindowsLogSumGroupByDevName(searchobj = {}) {
      let arr = []
      const data = {
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || '',
          EndTime: this.searchform.timeRange?.[1] || '',
          DeviceUUID: this.searchform.DeviceUUID,
          EventID: (this.searchform.EventID == null || this.searchform.EventID === '') ? '' : this.searchform.EventID == 0 ? 0xFFFFFFFF : this.searchform.EventID * 1,
          EventType: this.searchform.EventType,
          Level: this.searchform.Level,
          UserName: this.searchform.UserName,
          Descp: this.searchform.Descp,
          ...searchobj
        }
      }
      const res = await connrequest('GetWindowsLogSumGroupByDevName', data)
      res.Data = res.Data || []
      res.Data.map(item => {
        arr.push({ name: item.DeviceName, value: item.Count })
      })
      this.pie1Data = arr
    },
    async GetWindowsLogSumGroupBySource(searchobj = {}) {
      let arr = []
      const data = {
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || '',
          EndTime: this.searchform.timeRange?.[1] || '',
          DeviceUUID: this.searchform.DeviceUUID,
          EventID: (this.searchform.EventID == null || this.searchform.EventID === '') ? '' : this.searchform.EventID == 0 ? 0xFFFFFFFF : this.searchform.EventID * 1,
          EventType: this.searchform.EventType,
          Level: this.searchform.Level,
          UserName: this.searchform.UserName,
          Descp: this.searchform.Descp,
          ...searchobj
        }
      }
      const res = await connrequest('GetWindowsLogSumGroupBySource', data)
      res.Data = res.Data || []
      res.Data.map(item => {
        arr.push({ name: item.Source || '未知来源', value: item.Count })
      })
      this.pie2Data = arr.splice(0, 10)
    },
    async GetWindowsLogSumGroupByEventType(searchobj = {}) {
      let arr = []
      const data = {
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || '',
          EndTime: this.searchform.timeRange?.[1] || '',
          DeviceUUID: this.searchform.DeviceUUID,
          EventID: (this.searchform.EventID == null || this.searchform.EventID === '') ? '' : this.searchform.EventID == 0 ? 0xFFFFFFFF : this.searchform.EventID * 1,
          EventType: this.searchform.EventType,
          Level: this.searchform.Level,
          UserName: this.searchform.UserName,
          Descp: this.searchform.Descp,
          ...searchobj
        }
      }
      const res = await connrequest('GetWindowsLogSumGroupByEventType', data)
      res.Data = res.Data || []
      res.Data.map(item => {
        let EventType = this.EventTypeFormatter({ EventType: item.EventType })
        arr.push({ name: EventType, value: item.Count })
      })
      this.pie3Data = arr
    },
    async GetWindowsLogSumGroupByEventLevel(searchobj = {}) {
      let arr = []
      const data = {
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || '',
          EndTime: this.searchform.timeRange?.[1] || '',
          DeviceUUID: this.searchform.DeviceUUID,
          EventID: (this.searchform.EventID == null || this.searchform.EventID === '') ? '' : this.searchform.EventID == 0 ? 0xFFFFFFFF : this.searchform.EventID * 1,
          EventType: this.searchform.EventType,
          Level: this.searchform.Level,
          UserName: this.searchform.UserName,
          Descp: this.searchform.Descp,
          ...searchobj
        }
      }
      const res = await connrequest('GetWindowsLogSumGroupByEventLevel', data)
      res.Data = res.Data || []
      res.Data.map(item => {
        let Level = this.LevelFormatter({ Level: item.EventLevel })
        arr.push({ name: Level, value: item.Count })
      })
      this.pie4Data = arr
    },
    tabClick(row) {
      this.tabTitle = row.label
      switch (row.label) {
        case '按日统计分析':
          this.GetWindowsLogSumGroupByDate({ ...this.searchobj, ...this.nodeobj })
          break;
        case '按资产名称统计分析':
          this.GetWindowsLogSumGroupByDevName({ ...this.searchobj, ...this.nodeobj })
          break;
        case '按来源统计分析':
          this.GetWindowsLogSumGroupBySource({ ...this.searchobj, ...this.nodeobj })
          break;
        case '按事件类型统计分析':
          this.GetWindowsLogSumGroupByEventType({ ...this.searchobj, ...this.nodeobj })
          break;
        case '按事件等级统计分析':
          this.GetWindowsLogSumGroupByEventLevel({ ...this.searchobj, ...this.nodeobj })
          break;
      }
    },
    echartsClick(val, title) {
      this.pageNum = 1
      if (title === '按日统计分析') {
        this.echartsobj = { StartTime: `${val} 00:00:00`, EndTime: `${val} 23:59:59` }
        this.GetEventLog({ ...this.searchobj, ...this.nodeobj, ...this.echartsobj })
      } else if (title === '按资产名称统计分析') {
        this.echartsobj = { DeviceUUID: this.devices.find(item => item.DeviceName === val)?.DeviceUUID }
        this.GetEventLog({ ...this.searchobj, ...this.nodeobj, ...this.echartsobj })
      } else if (title === '按来源统计分析') {
        this.echartsobj = { Source: val }
        this.GetEventLog({ ...this.searchobj, ...this.nodeobj, ...this.echartsobj })
      } else if (title === '按事件类型统计分析') {
        const EventTypeMap = {
          '应用程序': 1,
          '安全': 2,
          'Setup': 3,
          '系统': 4,
          '转发事件': 5,
          '应用程序和服务日志': 6
        };
        this.echartsobj = { EventType: EventTypeMap[val] }
        this.GetEventLog({ ...this.searchobj, ...this.nodeobj, ...this.echartsobj })
      } else if (title === '按事件等级统计分析') {
        const levelMap = {
          '关键': 1,
          '错误': 2,
          '警告': 3,
          '信息': 4,
          '详细': 5,
          '审核成功': 6,
          '审核失败': 7,
        };
        this.echartsobj = { Level: levelMap[val] }
        this.GetEventLog({ ...this.searchobj, ...this.nodeobj, ...this.echartsobj })
      }
    },
    // 搜索
    search(val) {
      this.pageNum = 1
      this.searchobj = { ...val, EventID: (val.EventID == null || val.EventID === '') ? '' : val.EventID == 0 ? 0xFFFFFFFF : val.EventID * 1, }
      this.searchform = { ...val, EventID: (val.EventID == null || val.EventID === '') ? '' : val.EventID == 0 ? 0xFFFFFFFF : val.EventID * 1, }
      if (this.searchform.timeRange) {
        this.searchobj = { ...this.searchobj, StartTime: this.searchform?.timeRange[0] || '', EndTime: this.searchform?.timeRange[1] || '' }
      }
      this.getData({ ...this.echartsobj, ...this.searchobj, ...this.nodeobj })
      this.initData({...this.searchobj})
    },
    // 重置
    reset() {
      let endTime = new Date(new Date().setHours(0, 0, 0, 0)).getTime()
      let startTime = endTime - ((Cookies.get('Zhuoguan_DefaultLogDays') || 7) * 24 * 3600 * 1000);
      let arr = [parseTime(startTime), '']
      this.pageNum = 1
      this.formOptions = this.formOptions.map(item => {
        if (item.label === "日期") {
          item.initValue = arr
        }
        return item
      })
      this.searchform = {}
      this.echartsobj = {}
      this.searchobj = {}
      this.nodeobj = {}
      this.$set(this.searchform, 'timeRange', arr)
      this.$set(this.searchform, 'result', 2)
      this.$refs.connsearch.addInitValue()
      this.getData()
      this.initData()
    },
    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.pageNum = 1
      this.GetEventLog({ ...this.searchobj, ...this.echartsobj, ...this.nodeobj })
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum
      this.GetEventLog({ ...this.searchobj, ...this.echartsobj, ...this.nodeobj })
    }
  }
};
</script>
<style lang="scss" scoped>
@import "~@/styles/variables.scss";
@import "./components/css/conncss.scss";
</style>